package com.web.netty;

import com.web.netty.domain.Token;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;

import static com.web.netty.thread.NettyInThread.show;

@ChannelHandler.Sharable
@Component
public class ChannelInboundHandler extends ChannelInboundHandlerAdapter {
    @Autowired
    private Map<String, Channel> channelMap;

    @Qualifier("getInQueue")
    @Autowired
    private LinkedBlockingQueue<byte[]> inQueue;


    @Value("${gateWayBridge.ip}")
    private String gateWayBridgeIp;

    //表示 Channel 处于活跃状态 ，提示xx上线
    @Override
    public void channelActive(ChannelHandlerContext ctx)   {
        System.out.println(ctx.channel().remoteAddress() + " 上线了~");
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        channelMap.put(clientIp, ctx.channel());
    }

    //收到消息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] req = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(req);
        inQueue.put(req);
//        System.out.println("收到了消息！！！！！！！！！！！！！！！！");
//        show(req);
        byteBuf.release();
    }
    //    @Override
//    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
//        System.out.println("channel移除了");
//
//    }
//    @Override
//    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
//        System.out.println("channel注册了");
//    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        System.out.println("channel 不活跃，断开连接");
        channelMap.remove(clientIp);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
